package com.hjy.wechatdevelopermode.process;

import com.alibaba.fastjson.JSON;
import com.hjy.wechatdevelopermode.util.MessageUtil;
import com.hjy.wechatdevelopermode.requestMessage.TextMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类名: CoreService </br>
 * 描述: 核心服务类 </br>
 */
@Component
public class CoreService {
    private static final Logger logger = LoggerFactory.getLogger(CoreService.class);

//    @Autowired
//    private WechatdeveloperConfigService wechatdeveloperConfigService;
//    @Autowired
//    private RedisService redisService;


    /**
     * 处理微信发来的请求
     * @param request
     * @return xml
     */
    public  String processRequest(HttpServletRequest request) {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent = "欢迎您！";
        try {
            // 调用parseXml方法解析请求消息
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            logger.info("微信传入的用户消息为:requestMap={}", JSON.toJSONString(requestMap));
            // 发送方帐号 就是用户的openID
            String fromUserName = requestMap.get("FromUserName");
            // 开发者微信号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");

            // 回复文本消息
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(System.currentTimeMillis());
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
             //   respContent = "您发送的是文本消息！";
            }
            // 图片消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
//                respContent = "您发送的是图片消息！";
            }
            // 语音消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
//                respContent = "您发送的是语音消息！";
            }
            // 视频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
//                respContent = "您发送的是视频消息！";
            }
            // 视频消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_SHORTVIDEO)) {
//                respContent = "您发送的是小视频消息！";
            }
            // 地理位置消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
//                respContent = "您发送的是地理位置消息！";
            }
            // 链接消息
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
//                respContent = "您发送的是链接消息！";
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get("Event");
                String eventKey = requestMap.get("EventKey");
                // 关注 "CreateTime":"1590386607","EventKey":"","Event":"subscribe","ToUserName":"gh_0f9703c459e3","FromUserName":"oMiGPuKU4Jt6OdNLosDyYNd168nY","MsgType":"event"
                // "Ticket":"gQE18DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyaTV5bzA3T3hhZlUxX1lyUjF1MXYAAgT8Ts5eAwQAjScA","CreateTime":"1590579503","EventKey":"qrscene_1","Event":"subscribe","ToUserName":"gh_0f9703c459e3","FromUserName":"oMiGPuKU4Jt6OdNLosDyYNd168nY","MsgType":"event"
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    logger.info("有用户关注啦...................openId={}",fromUserName);
                    respContent = "谢谢您的关注！";
                    //新增
                    if(StringUtils.isNotBlank(eventKey)){
                        //关注的EventKey,qrscene_为前缀,后面是二维码的参数值
                        eventKey = eventKey.substring(8,eventKey.length());
                        logger.info("用户通过扫描二维码进入并关注公众号,openId={},scene_id={}",fromUserName,eventKey);
                        //这里保存租户id是不是更好
          //              wechatdeveloperConfigService.addMemberSource(fromUserName,Integer.valueOf(eventKey));
                    }else{
                        logger.info("用户不是通过扫描二维码进入并关注公众号,openId={}",fromUserName);
          //              wechatdeveloperConfigService.addMemberSource(fromUserName,null);
                    }

                }
                // 取消关注   "CreateTime":"1590386502","EventKey":"","Event":"unsubscribe","ToUserName":"gh_0f9703c459e3","FromUserName":"oMiGPuKU4Jt6OdNLosDyYNd168nY","MsgType":"event"
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    logger.info("用户取消关注...........openId={}",fromUserName);
                    // TODO 取消订阅后用户不会再收到公众账号发送的消息，因此不需要回复
          //          wechatdeveloperConfigService.deleteMemberSource(fromUserName);
                }
                // 扫描带参数二维码 "Ticket":"gQE08TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyNHBPZTFRT3hhZlUxXzIwUjF1MUgAAgTCM85eAwQAjScA","CreateTime":"1590573666","EventKey":"2","Event":"SCAN","ToUserName":"gh_0f9703c459e3","FromUserName":"oMiGPuKU4Jt6OdNLosDyYNd168nY","MsgType":"event"
                else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
                    respContent = "谢谢您的扫描！";
//                    String key = MessageUtil.EVENT_TYPE_SCAN + "_weChat_developer_"+eventKey;
//                    AtomicInteger retryCount = (AtomicInteger) redisService.getObjectCache(key);
//                    if (retryCount == null) {
//                        retryCount = new AtomicInteger(0);
//                    }else{
//                        retryCount.incrementAndGet();
//                    }
//                    redisService.set(key, retryCount);
                    logger.info("有已关注的用户扫描二维码进入公众号.......openId={},scene_id={}",fromUserName,eventKey);
                    // TODO 处理扫描带参数二维码事件

                }
                // 上报地理位置
                else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
                    // TODO 处理上报地理位置事件
                }
                // 自定义菜单
                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    // TODO 处理菜单点击事件
                }
            }
            // 设置文本消息的内容
            textMessage.setContent(respContent);
            // 将文本消息对象转换成xml
            respXml = MessageUtil.messageToXml(textMessage);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("解析微信返回的消息错误......e={}",e);
        }
        return respXml;
    }
}
